<?php

declare(strict_types=1);

namespace app\api\controller;

use app\common\tool\Result;
use think\Response;
use app\common\model\News as NewsModel;

class News extends Base
{
    /**
     * 详情
     */
    public function info($id)
    {
        try {
            $info = NewsModel::where(['id' => $id, 'status' => 1])->find();
            if (empty($info)) {
                return Result::fail('信息不存在！');
            }
            $url = 'https://' . $_SERVER['SERVER_NAME'] . '/uploads/';
            $info->content = htmlspecialchars_decode(str_replace('/uploads/', $url, $info->content));
            $info->content = str_replace('\\', '', $info->content);
            $info->create_times = date('Y-m-d', strtotime($info->create_time));
            NewsModel::where(['id' => $id])->inc('hits', 1)->update();
            return Result::success('获取成功', $info);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 列表
     */
    public function getList($type, $page = 1): Response
    {
        try {
            if ($type) {
                $map[] = ['type', '=', $type];
            }
            $map[] = ['status', '=', 1];
            $list = NewsModel::getPageList($map, 'id,title,images,hits,sub_title,create_time', $page, 20);
            foreach ($list['data'] as &$v) {
                $v->create_times = date('Y-m-d', strtotime($v->create_time));
            }
            return Result::fastReturn($list);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 消息中心
     */
    public function getMessageList()
    {
        try {
            $param = $this->request->get();
            if ($param['type'] == 2) {
                $model = new \app\common\model\News;
                $map[] = ['status', '=', 1];
                $map[] = ['type', '=', 1];
                $field = 'id,title,sub_title as content,create_time';
            } else {
                $model = new \app\common\model\PreceptLog;
                $map[] = ['uid', '=', $this->user->id];
                $field = 'id,title,content,create_time';
            }
            $list = $model::getPageList($map, $field, $param['page'], 20, false);

            return Result::fastReturn($list);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
}
